package com.ld.common.model.json;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.annotation.JsonInclude;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * api放回结果类，支持返回文档描述的类
 * 
 * @ClassName ApiResult
 * @author <a href="mailto:donggongai@126.com" target="_blank">吕凯</a>
 * @date 2019年3月4日 下午1:10:56
 * 
 * @param <T>
 */
@JsonInclude(JsonInclude.Include.NON_NULL) // 配置上这个 参数带有null 的就会忽略掉
@ApiModel(value = "返回说明")
@Data
public class ApiResult<T> {
    @ApiModelProperty(value = "操作是否成功，true代表成功，false代表失败")
    private Boolean success = false;
    @ApiModelProperty(value = "code：200:成功,500查找失败,1001参数错误")
    private Integer code;
    @ApiModelProperty(value = "响应消息提示")
    private String message; // 与code有对应关系，message可能会变，code一般不变
    @ApiModelProperty(value = "返回对象")
    private T data; // 泛型可以显示model 中的model 级联注释

    public ApiResult() {

    }

    public ApiResult(T data) {
        this(true, HttpServletResponse.SC_OK, "Ok", data);
    }

    public ApiResult(Boolean success, Integer code, String msg) {
        this(success, code, msg, null);
    }

    public ApiResult(Boolean success, Integer code, String msg, T data) {
        this.success = success;
        this.code = code;
        this.message = msg;
        this.data = data;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static ApiResult ok() {
        return new ApiResult(null);
    }

    @SuppressWarnings("rawtypes")
    public static ApiResult ok(String msg) {
        return new ApiResult(true, HttpServletResponse.SC_OK, msg);
    }

    public static <T> ApiResult<T> ok(T data) {
        return new ApiResult<T>(data);
    }

    public static <T> ApiResult<T> ok(String msg, T data) {
        return new ApiResult<T>(true, HttpServletResponse.SC_OK, msg, data);
    }

    @SuppressWarnings("rawtypes")
    public static ApiResult err(String msg) {
        return new ApiResult(false, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static <T> ApiResult<T> err(String msg, T data) {
        return new ApiResult<T>(false, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg);
    }

}
